package com.czxttkl.measure;


import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Enumeration;

import com.czxttkl.measure.R;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.telephony.PhoneStateListener;
import android.telephony.SignalStrength;
import android.telephony.TelephonyManager;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.Menu;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity {
	OnClickListener listenerBattery = null;
	OnClickListener listenerSignal = null;
	Button buttonBattery;
	Button buttonSignal;
	static Bundle testBundle = new Bundle();
	// StringBuilder mTextView = new StringBuilder();
	private int intLevel;
	private int intScale;
	private int intHealth;
	private String strTechnology;
	private int intTemperature;
	private int intVoltage;
	private int ASU = 0;
	private int BitErrorRate = 0;
	private TelephonyManager telMgr;

	PhoneStateListener pStateListener = new PhoneStateListener() {
		@SuppressLint({ "NewApi", "NewApi" })
		@TargetApi(7)
		public void onSignalStrengthsChanged(SignalStrength signalStrength) {
			if (signalStrength.isGsm()) {
				ASU = signalStrength.getGsmSignalStrength();
				BitErrorRate = signalStrength.getGsmBitErrorRate();
			//	TextView mTextView = (TextView) findViewById(R.id.testInfo);
				testBundle.putString("ASU", String.valueOf(ASU));
				testBundle.putString("BER", String.valueOf(BitErrorRate));
			//	mTextView.append("GSM Signal Strength:" + ASU + "asu\n");
			//	mTextView.append("GSM Bit Error Rate:" + BitErrorRate + "\n");
			}
		}
	};

	private BroadcastReceiver mBatInfoReceiver = new BroadcastReceiver() {
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();

			if (Intent.ACTION_BATTERY_CHANGED.equals(action)) {
				intLevel = intent.getIntExtra("level", 0);
				intScale = intent.getIntExtra("scale", 100);
				intHealth = intent.getIntExtra("health", 0);
				strTechnology = intent.getStringExtra("technology");
				intTemperature = intent.getIntExtra("temperature", 0);
				intVoltage = intent.getIntExtra("voltage", 0);
				testBundle.putString("BatteryLevel", String.valueOf(intLevel));
				testBundle.putString("BatteryScale", String.valueOf(intScale));
				testBundle.putString("BatteryHealth", String.valueOf(intHealth));
				testBundle.putString("BatteryTemperature", String.valueOf(intTemperature));
				testBundle.putString("BatteryTechnology", strTechnology);
				testBundle.putString("BatteryVoltage", String.valueOf(intVoltage));

				TextView mTextView02 = (TextView) findViewById(R.id.testInfo);

				mTextView02.setText(getResources().getText(
						R.string.batterycontent)
						+ String.valueOf(intLevel * 100 / intScale) + "%\n");

				mTextView02.append("Battry Level:" + String.valueOf(intLevel)
						+ "\n");
				mTextView02.append("Battry Scale:" + String.valueOf(intScale)
						+ "\n");
				mTextView02.append("Battry Health:" + String.valueOf(intHealth)
						+ "\n");
				mTextView02.append("Battry Technology:" + strTechnology + "\n");
				mTextView02.append("Battry Temperature:"
						+ String.valueOf(intTemperature) + "\n");
			}
		}
	};

	public ArrayList<String> getLocalIpAddress() {
		TextView mTextView = (TextView) findViewById(R.id.testInfo);
		ArrayList<String> addressList = new ArrayList<String>();
		try {
			for (Enumeration<NetworkInterface> en = NetworkInterface
					.getNetworkInterfaces(); en.hasMoreElements();) {
				NetworkInterface intf = en.nextElement();
				for (Enumeration<InetAddress> enumIpAddr = intf
						.getInetAddresses(); enumIpAddr.hasMoreElements();) {
					InetAddress inetAddress = enumIpAddr.nextElement();
					if (!inetAddress.isLoopbackAddress()) {
						mTextView.append("IP address:  "
								+ inetAddress.getHostAddress().toString()
								+ "\n");
						addressList
								.add(inetAddress.getHostAddress().toString());
					}
				}
			}
		} catch (SocketException ex) {
			Log.e("getLocalIpAddress", ex.toString());
		}
		return addressList;
	}

	@SuppressWarnings("static-access")
	public void beginSimNetTest() {
		TextView mTextView = (TextView) findViewById(R.id.testInfo);
		mTextView.append("Sim Card State:");
		/* Obtain Sim Card State */
		if (telMgr.getSimState() == telMgr.SIM_STATE_READY) {
			testBundle.putString("SimState", "inserted");
			mTextView.append("inserted.\n");
		} else if (telMgr.getSimState() == telMgr.SIM_STATE_ABSENT) {
			testBundle.putString("SimState", "absent");
			mTextView.append("not inserted.\n");
		} else {
			testBundle.putString("SimState", "unknown");
			mTextView.append("unknown.\n");
		}

		mTextView.append("Sim Card Serial Number:\n");
		/* Obtain Sim Card Serial Number ICC identity ICCID */
		if (telMgr.getSimSerialNumber() != null) {
			testBundle.putString("ICCID", telMgr.getSimSerialNumber());
			mTextView.append(telMgr.getSimSerialNumber() + "\n");
		} else {
			testBundle.putString("ICCID", "null");
			mTextView.append("null.\n");
		}

		mTextView.append("Sim Card Operator Number:");
		/* Obtain Sim Card Operator Number */
		if (telMgr.getSimOperator() != "") {
			testBundle.putString("SimOpeNum", telMgr.getSimOperator());
			mTextView.append(telMgr.getSimOperator() + "\n");
		} else {
			testBundle.putString("SimOpeNum", "null");
			mTextView.append("null.\n");
		}

		mTextView.append("Sim Card Operator Name:");
		/* Obtain Sim Card Operator Name */
		if (telMgr.getSimOperatorName() != "") {
			testBundle.putString("SimOpeName", telMgr.getSimOperatorName());
			mTextView.append(telMgr.getSimOperatorName() + "\n");
		} else {
			testBundle.putString("SimOpeName", "null");
			mTextView.append("null.\n");
		}

		mTextView.append("Sim Card Country ISO:");
		/* Obtain Sim Card Country ISO */
		if (telMgr.getSimCountryIso() != "") {
			testBundle.putString("SimISO", telMgr.getSimCountryIso());
			mTextView.append(telMgr.getSimCountryIso() + "\n");
		} else {
			testBundle.putString("SimISO", "null");
			mTextView.append("null.\n");
		}

		mTextView.append("Device ID:");
		/* Obtain Device ID international mobile Equipment identity IMEI */
		if (telMgr.getDeviceId() != "") {
			testBundle.putString("IMEI", telMgr.getDeviceId());
			mTextView.append(telMgr.getDeviceId() + "\n");
		} else {
			testBundle.putString("IMEI", "null");
			mTextView.append("null.\n");
		}

		mTextView.append("Subscriber ID:");
		/* Obtain SubScriberId international mobiles subscriber identity IMSI */
		if (telMgr.getSubscriberId() != "") {
			testBundle.putString("IMSI", telMgr.getSubscriberId());
			mTextView.append(telMgr.getSubscriberId() + "\n");
		} else {
			testBundle.putString("IMSI", "null");
			mTextView.append("null.\n");
		}

		mTextView.append("Phone Type:");
		/* Obtain Phone Type */
		switch (telMgr.getPhoneType()) {
		case 2:
			testBundle.putString("PhoneType", "CDMA");
			mTextView.append("CDMA\n");
			break;
		case 1:
			testBundle.putString("PhoneType", "GSM");
			mTextView.append("GSM\n");
			break;
		case 0:
			testBundle.putString("PhoneType", "none");
			mTextView.append("none\n");
			break;
		case 3:
			testBundle.putString("PhoneType", "SIP");
			mTextView.append("SIP\n");
			break;
		}

		mTextView.append("MSISDN(Phone Num):");
		/* Obtain Line1 Number mobile subscriber ISDN MSISDN */
		if (telMgr.getLine1Number() != "") {
			testBundle.putString("MSISDN", telMgr.getLine1Number());
			mTextView.append(telMgr.getLine1Number() + "\n");
		} else {
			testBundle.putString("MSISDN", "null");
			mTextView.append("null.\n");
		}

		mTextView.append("Network Operator Number:");
		/* Obtain Sim Card Operator Number */
		if (telMgr.getNetworkOperator() != "") {
			testBundle.putString("NetworkOpeNum", telMgr.getNetworkOperator());
			mTextView.append(telMgr.getNetworkOperator() + "\n");
		} else {
			testBundle.putString("NetworkOpeNum", "null");
			mTextView.append("null.\n");
		}

		mTextView.append("Network Operator Name:");
		/* Obtain Sim Card Operator Name */
		if (telMgr.getNetworkOperatorName() != "") {
			testBundle.putString("NetworkOpeName",
					telMgr.getNetworkOperatorName());
			mTextView.append(telMgr.getNetworkOperatorName() + "\n");
		} else {
			testBundle.putString("NetworkOpeName", "null");
			mTextView.append("null.\n");
		}

		mTextView.append("Network Country ISO:");
		/* Obtain Network Country ISO */
		if (telMgr.getNetworkCountryIso() != "") {
			testBundle.putString("NetworkISO", telMgr.getNetworkCountryIso());
			mTextView.append(telMgr.getNetworkCountryIso() + "\n");
		} else {
			testBundle.putString("NetworkISO", "null");
			mTextView.append("null.\n");
		}

		mTextView.append("Network Type:");
		/* Obtain Network Type */
		switch (telMgr.getNetworkType()) {
		case 2:
			testBundle.putString("NetworkType", "EDGE");
			mTextView.append("EDGE\n");
			break;
		case 1:
			testBundle.putString("NetworkType", "GPRS");
			mTextView.append("GPRS\n");
			break;
		case 0:
			testBundle.putString("NetworkType", "unknown");
			mTextView.append("unknown\n");
			break;
		case 3:
			testBundle.putString("NetworkType", "UMTS");
			mTextView.append("UMTS\n");
			break;
		case 4:
			testBundle.putString("NetworkType", "CDMA");
			mTextView.append("CDMA\n");
			break;
		case 5:
			testBundle.putString("NetworkType", "EVDO0");
			mTextView.append("EVDO0\n");
			break;
		case 6:
			testBundle.putString("NetworkType", "EVDOA");
			mTextView.append("EVDOA\n");
			break;
		case 7:
			testBundle.putString("NetworkType", "1xRTT");
			mTextView.append("1xRTT\n");
			break;
		case 8:
			testBundle.putString("NetworkType", "HSDPA");
			mTextView.append("HSDPA\n");
			break;
		case 9:
			testBundle.putString("NetworkType", "HSUPA");
			mTextView.append("HSUPA\n");
			break;
		case 10:
			testBundle.putString("NetworkType", "HSPA");
			mTextView.append("HSPA\n");
			break;
		case 11:
			testBundle.putString("NetworkType", "IDEN");
			mTextView.append("IDEN\n");
			break;
		case 12:
			testBundle.putString("NetworkType", "EVDOB");
			mTextView.append("EVDOB\n");
			break;
		case 13:
			testBundle.putString("NetworkType", "LTE");
			mTextView.append("LTE\n");
			break;
		case 14:
			testBundle.putString("NetworkType", "EHRPD");
			mTextView.append("EHRPD\n");
			break;
		case 15:
			testBundle.putString("NetworkType", "HSPA+");
			mTextView.append("HSPA+\n");
			break;
		}

	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		new Thread(new MyThreadInit()).start();
		

		setContentView(R.layout.activity_main);
		TextView mTextView = (TextView) findViewById(R.id.testInfo);
		mTextView.setMovementMethod(ScrollingMovementMethod.getInstance());

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}

	public static Bundle getTestBundle() {
		return testBundle;
	}

	Handler myHandlerSimNetTest = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			// Ҫ��������
			beginSimNetTest();
		}
	};
	Handler myHandlerIpAddress = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			// Ҫ��������
			ArrayList<String> ipAddress = getLocalIpAddress();
			testBundle.putStringArrayList("IpAddress", ipAddress);
		}
	};
	Handler myHandlerInit = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			// Ҫ��������
			/* ע��һ��ϵͳ BroadcastReceiver����Ϊ���ʵ�ؼ���֮�� */
			registerReceiver(mBatInfoReceiver, new IntentFilter(
					Intent.ACTION_BATTERY_CHANGED));

			telMgr = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
			telMgr.listen(pStateListener,
					PhoneStateListener.LISTEN_SIGNAL_STRENGTHS);
			new Thread(new MyThreadSimNetTest()).start();
			new Thread(new MyThreadIpAddress()).start();
			
		}
	};

	class MyThreadSimNetTest implements Runnable {
		public void run() {
			Message msg = new Message();
			MainActivity.this.myHandlerSimNetTest.sendMessage(msg);// ֪ͨHandler����UI
		}
	}
	class MyThreadInit implements Runnable {
		public void run() {
			Message msg = new Message();
			MainActivity.this.myHandlerInit.sendMessage(msg);// ֪ͨHandler����UI
		}
	}
	class MyThreadIpAddress implements Runnable {
		public void run() {
			Message msg = new Message();
			MainActivity.this.myHandlerIpAddress.sendMessage(msg);// ֪ͨHandler����UI
		}
	}

}
